package com.hmall.user.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public KeyPair keyPair(JwtProperties properties) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
        // 获取keystore资源
        Resource keyStoreResource = properties.getLocation();
        String password = properties.getPassword();
        String alias = properties.getAlias();
        
        // 加载keystore
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (InputStream is = keyStoreResource.getInputStream()) {
            keyStore.load(is, password.toCharArray());
        }
        
        // 获取私钥
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
        
        // 获取公钥
        PublicKey publicKey = keyStore.getCertificate(alias).getPublicKey();
        
        // 创建并返回密钥对
        return new KeyPair(publicKey, privateKey);
    }
}